import {Component, Inject, Input, NgModule, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {ActivatedRoute, Router} from '@angular/router';
import {UtilityService} from '../../../service/utils.service';
import {OperatrModule} from '../../../service/operators';
import {NzModalService, NzNotificationService} from 'ng-zorro-antd';
import {appConfig} from '../../../service/common';
import * as _ from 'lodash';
import {CommondictServe} from '../../../service/commonDict';
import * as moment from 'moment';
import {DA_SERVICE_TOKEN, ITokenService} from '@delon/auth';
@Component({
  selector: 'app-operators',
  templateUrl: './operators.component.html',
  styleUrls: ['./operators.component.less']
})


@NgModule({
    providers: [
        UtilityService
    ],
})

export class OperatorsComponent implements OnInit {
    operator: OperatrModule = new OperatrModule();
    operatorAdd: OperatrModule = new OperatrModule();
    loading = false;
    isEdit = false; // 默认是修改
    page: any; // 翻页数据
    total: number; // 数据总数
    modalVisible = false;
    expandForm = false;
    data: any[] = []; // 表格数据
    configTitle: string; // 模态框标题
    listTitle: any;
    reactPassword: string; // 重置密码标题
    selectedRows: any; // 总数
    authStype = [
        { text: '密码', type: 'password' },
        { text: '动态密码', type: 'dynpassword' },
        { text: '验证码', type: 'captcha' },
        { text: 'LDAP认证', type: 'ldap' },
        { text: '指纹', type: 'fingerprint' },
        { text: '指纹卡', type: 'fingerprintcard' },
    ]

    status: any; // 操作员状态
    headerData = [  // 配置表头内容
        {value: '操作员姓名' , key: 'operatorName', isclick: false},
        {value: '登陆用户名', key: 'userId', isclick: true},
        {value: '操作员状态', key: 'operatorStatus', isclick: false},
        {value: '认证模式' , key: 'authMode', isclick: false},
        {value: '锁定次数限制', key: 'lockLimit', isclick: false},
        {value: '密码错误次数', key: 'errCount', isclick: false},
    ];

    buttons = [
        {key: 'add', value: '新增操作员' ,  buttonCode: appConfig.funcObject.operators.add}
    ]
    pageIndex = 1; // 当前页数
    iSlah = false ; // 验证是否重复登录用户名
    moreData = { morebutton: false
                }

    // 重置密码类
    resetPawword = {
        userId: '',
        operatorName: '',
        newPassword: '',
        repeatPassword: '',
        Password: '',

    }
    operactorInfo: any; // 操作员信息绑定
    resetPassword = false; // 默认不显示
    funcBhvList: any;
    constructor(
        private http: _HttpClient,
        private router: Router,
        private utilityService: UtilityService,
        private modal: NzModalService,
        private nznot: NzNotificationService,
        private commondict: CommondictServe,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    ) {
    }


    ngOnInit() {
        this.getData(); // 只会触发一次，但是ngchanges并不会触发咋办
        this.listTitle = {value: '修改', buttonCode: appConfig.funcObject.operators.edit}
        this.dictQueryKey();
        this.funcBhvList = this.tokenService.get().funcList;
    }


    // 根据key查询业务字典
    dictQueryKey() {
        this.commondict.queryDictKey(appConfig.dictKeyList.operatorStatus)
            .subscribe((val) => {
                this.status = val.result;
            })

        this.commondict.queryDictKey(appConfig.dictKeyList.authmode)
            .subscribe((val) => {
                this.authStype = val.result;
            })
    }


    // 初始化数据
    getData(option?) { // 初始化请求后台数据
        if (option) {
            this.pageIndex = 1;
        }

        this.page = {
            condition: this.objJson,
            page: {
                current: this.pageIndex,
                size: this.operator.size,
            }
        };
        this.utilityService.postData(appConfig.serverUrl + appConfig.API.acOperatorsList, this.page)
            .subscribe(
                (val) => {
                    this.data = val.result.records;
                    this.total = val.result.total;
                    for (let i = 0; i < this.data.length; i ++ ) {
                        if (this.data[i].operatorStatus === '锁定') {
                            val.result.records[i].buttonData = [ {key: 'Unlock', value: '解锁', if: false}, {key: 'clear', value: '注销', if: false}, {key: 'reactPass', value: '重置密码', if: false}];
                        } else if (this.data[i].operatorStatus === '退出') {
                            val.result.records[i].buttonData = [ {key: 'clear', value: '注销', if: false}, {key: 'reactPass', value: '重置密码', if: false}];
                        } else if (this.data[i].operatorStatus === '注销') {
                            val.result.records[i].buttonData = [ {key: 'renewopen', value: '重新启用', if: false}, {key: 'reactPass', value: '重置密码', if: false}];
                        } else if (this.data[i].operatorStatus === '停用') {
                            val.result.records[i].buttonData = [{key: 'open', value: '启用', if: false}, {key: 'clear', value: '注销', if: false}, {key: 'dels', value: '删除', if: false}, {key: 'reactPass', value: '重置密码', if: false}];
                        } else { // 正常状态只能重置密码
                            val.result.records[i].buttonData = [{key: 'reactPass', value: '重置密码', if: false}];
                        }
                    }

                }
            );
    }
    // 枚举值转换
    operStatue(event) {
        if (event.operatorStatus === '正常') {
            event.operatorStatus = 'login';
        } else if (event.operatorStatus === '注销') {
            event.operatorStatus = 'clear';
        } else if (event.operatorStatus === '锁定') {
            event.operatorStatus = 'lock';
        } else if (event.operatorStatus === '挂起') {
            event.operatorStatus = 'pause';
        }else if (event.operatorStatus === '退出') {
            event.operatorStatus = 'logout';
        }else if (event.operatorStatus === '停用') {
            event.operatorStatus = 'stop';
        }
    }
    operauthMode(event) {
        if (event.authMode === '密码') {
            event.authMode = 'password';
        } else if (event.authMode === '动态密码') {
            event.authMode = 'dynpassword';
        } else if (event.authMode === '验证码') {
            event.authMode = 'captcha';
        } else if (event.authMode === 'LDAP认证') {
            event.authMode = 'ldap';
        }else if (event.authMode === '指纹') {
            event.authMode = 'fingerprint';
        }else if (event.authMode === '指纹卡') {
            event.authMode = 'fingerprintcard';
        }
    }

    // 想一下，能否把这三个方法封装到一个ts里面，引入即可，不然每次都写着三个方法不太现实。
    // 列表组件传过来的内容
    addHandler(event) {
        this.iSlah = false;
        if (event === 'add') {
            this.operatorAdd = new OperatrModule(); //  新建的时候 清空 重新构建
            for (const key in this.operator) {
                delete this.operator[key];
            }
            this.operatorAdd.operatorStatus = 'stop';
            this.operatorAdd.lockLimit = 5;
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.configTitle = '新建操作员';
            this.isEdit = true;
        } else { // 代表修改，把修改的内容传递进去，重新渲染

            this.operStatue(event);
            this.operauthMode(event); // 枚举值转换
            event.createtime = moment(event.createtime).format('YYYY-MM-DD');
            console.log(event)
            this.operatorAdd = event;
            this.configTitle = '修改操作员';
            this.modalVisible = true;  // 此时点击了列表组件的新增，打开模态框
            this.isEdit = false;
        }
    }



    // 验证是否重复
    userIdCodeexit(appType, appCode) {
        if(appType === '新建操作员') {
            let objJson = {
                guid: '',
                userId: appCode
            }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.existAddUserId , objJson)
                .subscribe(
                    (sus) => {
                        if (sus.result) {
                            this.iSlah = true; // 重复
                        } else {
                            this.iSlah = false; // 不重复
                        }
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        } else {
            let objJson = {
                guid: this.operatorAdd.guid,
                userId: appCode
            }
            this.utilityService.postData(appConfig.serverUrl  + appConfig.API.existUpdateUserId , objJson)
                .subscribe(
                    (sus) => {
                        if (sus.result) {
                            this.iSlah = true; // 重复
                        } else {
                            this.iSlah = false; // 不重复
                        }
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                    }
                );
        }
    }


    // 列表传入的翻页数据
    monitorHandler(event) {
        this.pageIndex = event;
        this.getData();
    }

    selectedRow(event) {
        console.log(event); // 对齐进行出来，来判断按钮层是否显示
    }


    // 接受子组件删除的数据 单条还是多条
    deleatData(event) {
        this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.acOperatorsDel + '/' + event[0].guid)
            .subscribe(
                (val) => {
                    // 修改成功只和的处理逻辑
                    this.nznot.create('success', val.msg , val.msg);
                    if ( !(( this.total - 1) % 10)) {
                        // if ( !(( this.total - this.acfundata.length) % 10)) { // 支持批量删除的方法
                        this.operator.pi -- ;
                    }
                    this.getData();
                });

    }


    deleteBatch(event) {
        this.modal.open({
            title: '是否删除',
            content: '您是否确认删除这' + event.length + '条操作员吗?',
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
                let delarray = [];
                for( let i = 0; i < event.length; i++) {
                    delarray.push(event[i].guid);
                }
                let deletaObj = {
                    deleteList: delarray
                }
                this.utilityService.postData(appConfig.serverUrl + appConfig.API.operbathDel, deletaObj )
                    .subscribe(
                        (val) => {
                            this.getData();
                            this.selectedRows = [];
                            this.nznot.create('success', val.msg , val.msg);
                        },
                        (error) => {
                            this.nznot.create('error', error.msg , error.msg);
                        });
            },
            onCancel: () => {
                this.selectedRows = [];
                this.getData();
            }
        });
    }

    // 列表按钮方法
    buttonDataHandler(event) {
       console.log(event); // 根据event.value来判断不同的请求，来获取结果和方法或者进行路由的跳转
    }


    // 处理行为代码，跳转、弹出框、其他交互
    isActive(event) {
        // 跳转到操作员360导航
        let AppCode = appConfig.funcObject.operators.operatorsRole; // 暂无，先写应用的
        if(this.funcBhvList.indexOf(AppCode) >= 0) {
            // 路由跳转 跳转到对应的功应用页
            this.router.navigate(['operatorInfo'],
                { queryParams:
                        { operatorId: event.guid
                        }
                });
        } else {
            this.nznot.create('error', '无法跳转' , '您可能暂时没有权限');
        }
    }


    buttonEvent(event) {
        let datainfo = _.cloneDeep(event);
        this.operStatue(datainfo)
          if (event.names) {
              if (event.names.key !== 'dels' && event.names.key !== 'reactPass') {
                  let status = {
                      guid: datainfo.guid,
                      operatorStatus: event.names.key
                  };
                  if(event.names.key === 'open') { // 停用状态下，启用到退出
                      status.operatorStatus = 'logout';
                      this.utilityService.putData(appConfig.serverUrl + appConfig.API.startOperatorStatus, status)
                          .subscribe(
                              (val) => {
                                  this.nznot.create('success', val.msg , val.msg);
                                  this.getData()
                              },
                              (error) => {
                                  this.nznot.create('error', error.msg , error.msg);
                              }
                          );
                  }
                  if(event.names.key === 'clear') { // 注销
                      status.operatorStatus = 'clear';
                      this.utilityService.putData(appConfig.serverUrl + appConfig.API.cancelOperatorStatus, status)
                          .subscribe(
                              (val) => {
                                  this.nznot.create('success', val.msg , val.msg);
                                  this.getData()
                              },
                              (error) => {
                                  this.nznot.create('error', error.msg , error.msg);
                              }
                          );
                  }
                  if(event.names.key === 'Unlock') { // 锁定下，解锁
                      status.operatorStatus = 'logout';
                      this.utilityService.putData(appConfig.serverUrl + appConfig.API.deblockOperatorStatus, status)
                          .subscribe(
                              (val) => {
                                  this.nznot.create('success', val.msg , val.msg);
                                  this.getData()
                              },
                              (error) => {
                                  this.nznot.create('error', error.msg , error.msg);
                              }
                          );
                  }
                  if(event.names.key === 'renewopen') { // 重新启用--- 到停用
                      status.operatorStatus = 'stop';
                      this.utilityService.putData(appConfig.serverUrl + appConfig.API.restartOperatorStatus, status)
                          .subscribe(
                              (val) => {
                                  this.nznot.create('success', val.msg , val.msg);
                                  this.getData()
                              },
                              (error) => {
                                  this.nznot.create('error', error.msg , error.msg);
                              }
                          );
                  }

              } else {
                  if (event.names.key === 'dels') {
                      this.utilityService.deleatData(appConfig.serverUrl + appConfig.API.acOperatorsDel + '/' + event.guid)
                          .subscribe(
                              (src) => {
                                  // 修改成功只和的处理逻辑
                                  this.nznot.create('success', src.msg , src.msg);
                                  if ( !(( this.total - 1) % 10)) {
                                      // if ( !(( this.total - this.acfundata.length) % 10)) { // 支持批量删除的方法
                                      this.operator.pi -- ;
                                  }
                                  this.getData();
                              });
                  } else if (event.names.key === 'reactPass') { // 重置密码
                      this.resetPawword.userId = event.userId;
                      this.resetPawword.operatorName = event.operatorName;
                     this.operactorInfo = event;
                      this.resetPassword = true;
                     this.reactPassword = '为操作员[' + event.operatorName + ']重置密码';
                  }
              }
              }
    }


    resetPas() {
        const jsonObj = {
            userId: this.resetPawword.userId,
            operatorName: this.resetPawword.operatorName,
            newFirstPassword: this.resetPawword.newPassword,
            newSecondPassword: this.resetPawword.repeatPassword,
        }
        this.utilityService.putData(appConfig.serverUrl + appConfig.VAPi.vresetPassword, jsonObj )
            .subscribe(
                (val) => {
                    this.resetPassword = false;
                    this.nznot.create('success', val.msg , val.msg);
                },
                (error) => {
                    this.nznot.create('error', error.msg , error.msg);
                    this.resetPassword = false;
                });
    }


    objJson = {};
    // 搜索框
    search() {
        this.objJson = this.operator;
        this.getData(this.operator);
        this.operator.pi = 1;
    }


    // 重置搜索框
    reset() {
        this.operator = new OperatrModule();
        this.objJson = {};
        this.getData();
    }

    // 弹出框保存组件
    save() {
        const jsonObj  = this.operatorAdd;
        console.log(jsonObj)
        if (!jsonObj.invalDate) {
            jsonObj.invalDate = moment(new Date()).format('YYYY-MM-DD'); // 默认当前时间
        }
        if (this.isEdit) { // 新增
            this.utilityService.postData(appConfig.serverUrl + appConfig.API.acOperatorsAdd, jsonObj, )
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                    },
                    (error) => {
                        this.nznot.create('success', error.msg , error.msg);
                        this.getData();
                    }
                );
        } else { // 修改
            this.utilityService.putData(appConfig.serverUrl + appConfig.API.acOperatorsDel, jsonObj)
                .subscribe(
                    (val) => {
                        this.nznot.create('success', val.msg , val.msg);
                        this.getData();
                    },
                    (error) => {
                        this.nznot.create('error', error.msg , error.msg);
                        this.getData();
                    }
                );
        }
        this.modalVisible = false;
    }


    cencel() {
        this.modalVisible = false;
        this.getData();
    }


}
